package com.hoelg.hgc.webservices;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.hoelg.hgc.DAO.HGCUser;
import com.hoelg.hgc.constants.Utils;

public class ConnexionUtilisateur extends WebServiceHGC {

	private static final String WS_NAME = "getUser";

	private String shaoneizedpwd;
	
	public ConnexionUtilisateur(String login, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
		super(WS_NAME);
		try {
			this.webServiceParams.add(new BasicNameValuePair("u", login));
			shaoneizedpwd = Utils.SHA1(password);
			this.webServiceParams.add(new BasicNameValuePair("p", shaoneizedpwd));
		} catch (Exception e) {
			Log.e("connexionutilisateur_connexionutilisateur", "Creation webService Connexion Utilisateur, catched : " + e.toString());
		}

	}

	public Object executeWebService() {

		beforeExec();

		try {
			super.executeWebServiceBase();

			JSONArray jArray = Utils.parseJSON(this.result);

			if (jArray.length() >0) {
				if (jArray.length() == 1 ) {
					JSONObject json_data = jArray.getJSONObject(0);
					if(json_data.length() == 2){
						String status = json_data.getString("status");
						if (status.equals("OK")) {
							JSONObject userJSON = json_data.getJSONObject("details");
							if (null != userJSON){
								if(userJSON.length() == 3){
									HGCUser.setInstance(Integer.parseInt(userJSON.getString("id")), 
											userJSON.getString("login"), userJSON.getDouble("balance"),
											shaoneizedpwd);
									HGCUser connectedUser = HGCUser.getInstance();

									resultatWS = connectedUser.ConfirmConnection();
								}							
							}
							else{
								resultatWS = "unKnown user";
							}
						}
						else{
							String error = json_data.getString("details");
							resultatWS = "error : " + error;
						}
					}
				}
				else{
					resultatWS = "multipleUser";
				}
			}
			else{
				resultatWS = "emptyResult";
			}
		}
		catch(Exception e){
			Log.e("connexionutilisateur_executewebservice","erreur catch�e dans " + WS_NAME + " : " + e.toString());
		}



		afterExec();

		return null;

	}

}
